<template>
  <div class="node-toolbar">
    <button
      v-if="showExecute"
      class="tb-btn"
      title="执行"
      @click.stop="handleExecute"
    >
      执
    </button>

    <button
      v-if="showMute"
      class="tb-btn"
      :title="muted ? '取消屏蔽' : '屏蔽'"
      @click.stop="handleToggleMute"
    >
      {{ muted ? "解" : "屏" }}
    </button>

    <button
      v-if="showDelete"
      class="tb-btn danger"
      title="删除"
      @click.stop="handleDelete"
    >
      删
    </button>
  </div>

  <!-- 屏蔽后弹出：设置节点输出文本 -->
  <a-modal
    v-model:visible="showOutputsModal"
    title="设置节点输出"
    :mask-closable="false"
    ok-text="保存"
    cancel-text="取消"
    :on-before-ok="beforeOk"
  >
    <div v-if="outputsDraft.length">
      <div
        v-for="(op, idx) in outputsDraft"
        :key="op.name || idx"
        style="
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 10px;
        "
      >
        <span style="min-width: 64px; color: #64748b">{{ op.name }}</span>
        <a-input
          v-model="op.value"
          placeholder="请输入变量默认值"
          allow-clear
          :status="!op.value || !String(op.value).trim() ? 'error' : undefined"
          style="flex: 1"
        />
      </div>
    </div>
    <div v-else style="color: #999">此节点暂无可配置的输出。</div>
  </a-modal>
</template>

<script setup lang="ts">
import { useVueFlow } from "@vue-flow/core";
import { ref } from "vue";
import { Message } from "@arco-design/web-vue";

interface Props {
  nodeId?: string;
  showExecute?: boolean;
  showMute?: boolean;
  showDelete?: boolean;
  muted?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  nodeId: "",
  showExecute: false,
  showMute: false,
  showDelete: true,
  muted: false,
});

const { findNode, removeNodes } = useVueFlow();

function handleExecute() {
  try {
    const id = String(props.nodeId || "");
    const n = id ? findNode(id) : null;
    if (n) (n as any).data.executed = true;
  } catch (e) {}
}

function handleToggleMute() {
  try {
    const id = String(props.nodeId || "");
    const n = id ? findNode(id) : null;
    if (n) {
      const next = !Boolean((n as any).data?.muted);
      (n as any).data.muted = next;
      // 打开输出设置弹窗（仅在屏蔽时弹出）
      if (next) {
        const list = Array.isArray((n as any).data?.outputs)
          ? JSON.parse(JSON.stringify((n as any).data.outputs))
          : [];
        outputsDraft.value = list;
        if (list.length > 0) {
          showOutputsModal.value = true;
        }
      }
    }
  } catch (e) {}
}

function handleDelete() {
  try {
    const id = String(props.nodeId || "");
    if (id) removeNodes([id]);
  } catch (e) {}
}

// 弹窗及数据
const showOutputsModal = ref(false);
const outputsDraft = ref<Array<{ key: string; name?: string; value?: string }>>(
  []
);

async function beforeOk() {
  try {
    const id = String(props.nodeId || "");
    const n = id ? findNode(id) : null;
    if (!n) return true;
    // 校验：所有 name、value 必填
    const list = Array.isArray(outputsDraft.value) ? outputsDraft.value : [];
    const invalid = list.find(
      (it: any) =>
        !it || !String(it?.name ?? "").trim() || !String(it?.value ?? "").trim()
    );
    if (list.length > 0 && invalid) {
      Message.error("请填写所有输出名称与输出值");
      return false; // 阻止关闭
    }
    // 保存到 JSON
    (n as any).data.outputs = list.map((it: any) => ({
      key: String(it?.key || ""),
      name: String((it?.name ?? "").trim()),
      value: String((it?.value ?? "").trim()),
    }));
    return true;
  } catch (e) {
    return false;
  }
}
</script>

<style scoped>
.node-toolbar {
  position: absolute;
  top: 6px;
  right: 6px;
  display: none;
  gap: 6px;
  z-index: 2;
}
.tb-btn {
  padding: 2px 6px;
  font-size: 12px;
  line-height: 1;
  border: 1px solid #e5e7eb;
  border-radius: 10px;
  background: #fff;
  color: #334155;
}
.tb-btn:hover {
  background: #f3f4f6;
}
.tb-btn.danger {
  color: #f53f3f;
  border-color: #fecaca;
}
</style>

<style>
/* 全局遮罩样式：供所有节点复用，避免重复定义 */
.mute-mask {
  position: absolute;
  inset: 0;
  border-radius: 14px;
  background: rgba(245, 63, 63, 0.26);
  outline: 3px solid #f53f3f;
  box-shadow: inset 0 0 0 3px rgba(245, 63, 63, 0.32);
  z-index: 1; /* 确保工具栏(2)在其上方 */
  pointer-events: none;
}
</style>
